import {
    hisInfoType, sourceType,
    playInfoType, songsInfoPlayType, partStateType, dispatchType,
    stateType,
    likeSongType
} from '@/interfaces/types'
import {getPlaylistDetail} from '@/api'
/*########################无耦合操作####################################*/
/********************播放历史操作*****************************************/
const addHistory = (tid: number, tsource: sourceType, state: stateType)
    : { songsInfoHis: Array<hisInfoType>, sIHC: boolean } => {
    let arrs: Array<hisInfoType>
    if (state?.songsInfoHis?.length > 0) {
        //判断相同id并删除原有id
        arrs = state.songsInfoHis
        try {
            for (let index = 0; index < arrs.length; index++) {
                if (arrs[index].id === tid) {
                    arrs.splice(index, 1)
                    break
                }
            }
        } catch (err) {
            console.log(err);
        }
    } else {
        arrs = []
    }
    return {
        songsInfoHis: [{ id: tid, source: tsource, playTimeMS: new Date().getTime() }, ...arrs],
        sIHC: !state.sIHC
    }
}
/********************播放列表操作*****************************************/
const setPlays = (ids: Array<number>, tsource: sourceType, state: stateType)
    : partStateType => {
    let arrs: Array<songsInfoPlayType> = []
    ids.map((res: number) => {
        arrs.push({ id: res, source: tsource })
    })
    return {
        songsInfoPlay: arrs,
        sIPC: !state.sIPC
    }
}
const addPlays = (tid: number, tsource: sourceType, state: stateType)
    : { songsInfoPlay: Array<songsInfoPlayType>, sIPC: boolean } => {
    let arrs: Array<songsInfoPlayType> = []
    if (state?.songsInfoPlay?.length > 0) {
        arrs = state.songsInfoPlay
        try {
            if (getIndexById(tid, state.songsInfoPlay) < 0) {
                arrs = [{ id: tid, source: tsource }, ...arrs]
            }
        } catch (err) {
            console.log(err);
        }
    }
    return {
        songsInfoPlay: [...arrs],
        sIPC: !state.sIPC
    }
}
/*********************操作喜欢的音乐*******************************************/
const addLikeSong
    = (id: number, likeSong: Array<likeSongType>)
        : Array<likeSongType> => {
        return [{ id: id }, ...likeSong]
    }
const deleteLikeSong
    = (id: number, likeSong: Array<likeSongType>)
        : Array<likeSongType> => {
        for (let i = 0; i < likeSong.length; i++) {
            if (likeSong[i]?.id === id) {
                likeSong.splice(i, 1)
                return likeSong
            }
        }
        return likeSong
    }
/********************播放歌单中歌曲操作,不改变歌单*****************************************/
const setPlayIndex = (tindex: number, tid: number)
    : { playInfo: playInfoType } => {
    return {
        playInfo: { playingId: tid, isPlay: true, playingIndex: tindex, currentTime: 0 }
    }
}
/*########################定制操作####################################*/
//
const getIndexById = (tid: number, tsongsInfoPlay: Array<songsInfoPlayType>)
    : number => {
    let arrs = tsongsInfoPlay
    let index = -1
    try {
        for (let i = 0; i < arrs.length; i++) {
            if (arrs[i].id === tid) {
                index = i
                break
            }
        }
    } catch (err) {
        console.log(err);
    }
    return index
}
export const setPlayIndexInList = (tindex: number, tstate: stateType)
    : Promise<dispatchType | null> => {
    let tid: number = tstate.songsInfoPlay[tindex].id
    let tsource: sourceType = tstate.songsInfoPlay[tindex].source
    let objDisp: dispatchType = {
        type: 'SET_STATE',
        value: {
            ...addHistory(tid, tsource, tstate),
            ...setPlayIndex(tindex, tstate.songsInfoPlay[tindex].id)
        }
    }
    return new Promise((resolve) => {
        resolve(objDisp)
    })
}
export const setPlayList = (tids: Array<number>, tsource: sourceType, state: stateType)
    : Promise<dispatchType | null> => {
    let obj: dispatchType = {
        type: 'SET_STATE',
        value: {
            ...setPlays(tids, tsource, state),
            ...addHistory(tids[0], tsource, state),
            ...setPlayIndex(0, tids[0])
        }
    }
    return new Promise((resolve) => {
        resolve(obj)
    })
}
export const changePlayingSong = (changCount: number, tstate: stateType)
    : Promise<dispatchType | null> => {
    return new Promise((resolve) => {
        let maxIndex = tstate.songsInfoPlay.length - 1
        if (maxIndex <= 0 || changCount === 0) {
                resolve(null)
        }
        let playingIndex: number = tstate.playInfo.playingIndex || 0
        playingIndex = playingIndex + changCount
        if (playingIndex < 0) {
            playingIndex = maxIndex + 1 + playingIndex
        } else if (playingIndex > maxIndex) {
            playingIndex = playingIndex - maxIndex - 1
        }
        let disObj: dispatchType | null = null
        setPlayIndexInList(playingIndex, tstate).then((res => {//************加同步解决***********
            resolve(res)
        }))
    })
}
export const addNewPlayId = (tid: number, tsource: sourceType, tstate: stateType)
    : Promise<dispatchType | null> => {
    let playIndex = getIndexById(tid, tstate.songsInfoPlay)
    playIndex = playIndex < 0 ? 0 : playIndex
    let objDisp: dispatchType = {
        type: 'SET_STATE',
        value: {
            ...addPlays(tid, tsource, tstate),
            ...addHistory(tid, tsource, tstate),
            ...setPlayIndex(playIndex, tid)
        }
    }
    return new Promise((resolve) => {
        resolve(objDisp)
    })
}
export const playMusicsByPlaylistId = (id:number, tsource: sourceType, state: stateType)
:Promise<dispatchType>=>{
    return new Promise((resolve,reject)=>{
        getPlaylistDetail({ id: id }).then((res: any) => {
            if(res?.playlist?.trackIds?.length > 0){
            let ids:Array<number> = []
              if(res?.playlist?.trackIds?.length > 100){
                res?.playlist?.trackIds?.splice(100)//限制加入100首
              }
              res?.playlist?.trackIds?.map((resId:{id:number})=>{
                ids.push(resId.id)
              })
              setPlayList(ids,{text:'歌单页面',href:'优化项'},state).then(result =>{
                // console.log(result);
                if(result){
                    resolve(result)
                }else{
                    reject('Error:playMusicsByPlaylistId')
                }
              }).catch((err)=>{
                console.log(err);
              })
            }
          });
    })
}